package com.bayair.doctor.ui.main;

import android.Manifest;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;

import com.bayair.doctor.R;
import com.bayair.doctor.biz.im_helper.IMHelper;
import com.bayair.doctor.mvp.BaseMVPActivity;
import com.bayair.doctor.mvp.annotation.InjectPresenter;
import com.bayair.doctor.ui.main.center.CenterFragment;
import com.bayair.doctor.ui.main.left.LeftFragment;
import com.bayair.doctor.ui.main.right.RightFragment;
import com.bayair.doctor.utils.ActivityStackManager;
import com.bayair.doctor.utils.DoubleClickHelper;
import com.bayair.doctor.utils.permisstion.PermissionUtils;
import com.next.easynavigation.constant.Anim;
import com.next.easynavigation.view.EasyNavigationBar;
import com.tencent.qcloud.tim.uikit.modules.chat.GroupChatManagerKit;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationManagerKit;
import com.tencent.qcloud.tim.uikit.modules.conversation.interfaces.MessageUnreadWatcher;
import com.tencent.qcloud.tim.uikit.utils.FileUtil;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;

import butterknife.BindView;

public class MainActivity extends BaseMVPActivity implements MainContract.View, MessageUnreadWatcher {

    @BindView(R.id.navigationBar)
    EasyNavigationBar navigationBar;

    private String[] tabText = {"消息", "问诊", "我"};
    //未选中icon
    private int[] normalIcon = {R.drawable.menu_msg_n, R.drawable.menu_inquiry_center, R.drawable.menu_me_n};
    //选中时icon
    private int[] selectIcon = {R.drawable.menu_msg_s, R.drawable.menu_inquiry_center, R.drawable.menu_me_s};

    private List<Fragment> fragments = new ArrayList<>();

    private Animation translateAnimation;
    private boolean isShaking = false;

    @InjectPresenter
    MainPresenter mPresenter;

    //需要的权限读写必须，创建im缓存
    private String[] PERMISSIONS_All_NEED = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE,
    };

//    @Override
//    public boolean immersionBarEnabled() {
//        return false;
//    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        loadFragment();
        initCenterImageAnim();
    }

    @Override
    protected void initData() {
        mPresenter.flushToken();

        checkPermission();

        // 未读消息监视器
        ConversationManagerKit.getInstance().addUnreadWatcher(this);
        GroupChatManagerKit.getInstance();
    }

    @Override
    protected void onStop() {
        ConversationManagerKit.getInstance().destroyConversation();
        super.onStop();
    }

    /**
      网络状态由不可用转变为可用
     */
    @Override
    public void onAvailable(Network network, NetworkInfo networkInfo) {
        super.onAvailable(network, networkInfo);
        IMHelper.checkIMLogin();
    }

    @Override
    public void updateUnread(int count) {
        //未读消息
//        if (count > 0) {
//            mMsgUnread.setVisibility(View.VISIBLE);
//        } else {
//            mMsgUnread.setVisibility(View.GONE);
//        }
//        String unreadStr = "" + count;
//        if (count > 100) {
//            unreadStr = "99+";
//        }
//        mMsgUnread.setText(unreadStr);
    }

    private void checkPermission() {
        PermissionUtils.requestPermission(this, new PermissionUtils.OnRequestPermissionListener() {
            @Override
            public void onGranted() {
                // 从application移入到这里，原因在于首次装上app，需要获取一系列权限，如创建文件夹，图片下载需要指定创建好的文件目录，
                // 否则会下载本地失败，聊天页面从而获取不到图片、表情
                FileUtil.initPath();
            }

            @Override
            public void onDenied(boolean isAlways) {
            }
        }, PERMISSIONS_All_NEED);
    }

    /**
     * 晃动动画
     */
    private void initCenterImageAnim() {
        translateAnimation = new TranslateAnimation(0, 10, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(1));
        translateAnimation.setDuration(200);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                isShaking = true;
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                isShaking = false;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    private void loadFragment() {
        fragments.add(LeftFragment.newInstance());
        fragments.add(CenterFragment.newInstance());
        fragments.add(RightFragment.newInstance());

        navigationBar.titleItems(tabText)
                .normalIconItems(normalIcon)
                .selectIconItems(selectIcon)
                .fragmentList(fragments)
                .addLayoutRule(EasyNavigationBar.RULE_BOTTOM)//可以使图标超出底部tab高度
                .addLayoutBottom(0)//调节距离底部的距离
                .addAlignBottom(true)//调节是否与其他tab文字对齐
                .addAsFragment(true)//中间图标对应fragment切换
                .fragmentManager(getSupportFragmentManager())
                .onTabClickListener(new EasyNavigationBar.OnTabClickListener() {
                    @Override
                    public boolean onTabClickEvent(View view, int position) {
                        if (position == 1) {
                            post(() -> {
                                if (!isShaking) {
                                    navigationBar.getAddImage().startAnimation(translateAnimation);
                                }
                            });
                        }
                        return false;
                    }
                })
                .canScroll(true)//Viewpager能否左右滑动
                .mode(EasyNavigationBar.MODE_ADD) //默认MODE_NORMAL 普通模式  //MODE_ADD 带加号模式
                .anim(Anim.ZoomIn)//tab 动画
                .build();
        navigationBar.getmViewPager().setOffscreenPageLimit(3);
        navigationBar.selectTab(1);

//        //数字消息大于99显示99+ 小于等于0不显示，取消显示则可以navigationBar.setMsgPointCount(1, 0)
//        navigationBar.setMsgPointCount(1, 100);
//        navigationBar.setMsgPointCount(0, 1);
//        //红点提示 第二个参数控制是否显示
//        navigationBar.setHintPoint(3, true);
//        //清除第四个红点提示
//        navigationBar.clearHintPoint(3);
//        //清除第一个数字消息
//        navigationBar.clearMsgPoint(0);
    }

    @Override
    public void showLoadToken() {
        //showLoading();
    }

    @Override
    public void complete() {
        showComplete();
    }

    @Override
    public void onBackPressed() {
        if (DoubleClickHelper.isOnDoubleClick()) {
            //移动到上一个任务栈，避免侧滑引起的不良反应
            moveTaskToBack(false);
            postDelayed(() -> {
                // 进行内存优化，销毁掉所有的界面
                ActivityStackManager.getInstance().finishAllActivities();
                // 销毁进程（请注意：调用此 API 可能导致当前 Activity onDestroy 方法无法正常回调）
                // System.exit(0);
            }, 300);
        } else {
            toast("再按一次退出");
        }
    }
}
